package main

import (
	"errors"
	"fmt"
)

// 1.实现一个函数，接受若干个float64（用不定长参数），返回这些参数乘积的倒数，除数为0时返回error
func returnReciprocal(multiplies ...float64) (float64, error) {
	if len(multiplies) == 0 {
		return 0, errors.New("没有传入参数，无法返回乘积的倒数")
	}
	product := float64(1)
	for _, ele := range multiplies {
		//fmt.Println(ele)
		product *= ele
	}
	if product == 0 {
		return 0, errors.New("乘积为0，无法返回乘积的倒数")
	}
	return 1 / product, nil
}

// 2.上题用递归实现
func recursion_returnReciprocal(multiplies ...float64) (float64, error) {
	if len(multiplies) == 0 {
		return 0, errors.New("没有传入参数，无法返回乘积的倒数")
	}
	product := recursion_product(multiplies)
	if product == 0 {
		return 0, errors.New("乘积为0，无法返回乘积的倒数")
	}
	return 1 / product, nil
}

func recursion_product(multiplies []float64) float64 {
	if len(multiplies) == 1 {
		return multiplies[0]
	}
	if len(multiplies) == 2 {
		return multiplies[0] * multiplies[1]
	}
	product := float64(1)
	product = multiplies[0] * recursion_product(multiplies[1:len(multiplies)])
	return product
}

// 3.定义两个接口：鱼类和爬行动物，再定义一个结构体：青蛙，同时实现上述两个接口
type fish interface {
	swim(name string)
}

type reptile interface {
	crawl() bool
}

type frog struct {
	name string
}

func (litte_frog frog) swim(name string) {
	fmt.Printf("%s can swim", name)
}
func (little_frog frog) crawl() bool {
	return true
}

// 4.实现函数func square(num interface{}) interface{}，计算一个interface{}的平方，
//interface{}允许是4种类型：float32、float64、int、byte

func square(num interface{}) interface{} {
	switch v := num.(type) {
	case int:
		return v * v
	case byte:
		return v * v
	case float32:
		return v * v
	case float64:
		return v * v
	default:
		return "wrong type!"
	}
}

func main() {
	if res, err := returnReciprocal(); err == nil {
		fmt.Println(res)
	} else {
		fmt.Println(err)
	}

	if res, err := returnReciprocal(5, 6, 7, 9.5); err == nil {
		fmt.Println(res)
	} else {
		fmt.Println(err)
	}

	if res, err := returnReciprocal(5, 0, 7, 9.5); err == nil {
		fmt.Println(res)
	} else {
		fmt.Println(err)
	}

	if res, err := recursion_returnReciprocal(); err == nil {
		fmt.Println(res)
	} else {
		fmt.Println(err)
	}

	if res, err := recursion_returnReciprocal(5, 6, 7, 9.5); err == nil {
		fmt.Println(res)
	} else {
		fmt.Println(err)
	}

	if res, err := recursion_returnReciprocal(5, 0, 7, 9.5); err == nil {
		fmt.Println(res)
	} else {
		fmt.Println(err)
	}

	little_frog := frog{"little_frog"}
	little_frog.swim("little_frog")
	fmt.Println()
	fmt.Println(little_frog.crawl())

	fmt.Println(square(5))

}
